/* api */
import { 
  checkConnectorCard, 
  getModuleAppItemsList, 
  getModuleAppList, 
  getModuleAppListV2,
  getConnectorOptionsV2, 
  saveConnectorOptionsV2, 
  getEditConnectorOptionsV2 
} from '@src/modules/connector/api'

/* hooks */
import { useLoading } from '@hooks/useLoading'
/* model */
import { 
  ConnectorDefaultEditOptions,
  ConnectorDefaultOptions, 
  ConnectorEditOptions, 
  ConnectorModuleErrorMessageEnum, 
  ConnectorOptions,
  // ConnectorAppModule,
  ConnectorAppModuleListItem,
  ConnectorFetchAppModulesStorageKey
} from '@src/modules/connector/model'
import MsgModel from '@model/MsgModel'
/* vue */
import { Ref, ref } from 'vue'
/* types */
import { ConnectorGetEditOptionsParams, ConnectorGetModuleListParams, ConnectorGetOptionsParams, ConnectorSaveOptionsParams } from '@src/modules/connector/types'
/* util */
import { message } from '@src/util/message'
import Log from '@src/util/log'
import { connectorOptionsExtraCompatibleHandler, covertSetForDataKey } from '@src/modules/connector/util'
import { storageGet, storageSet } from '@src/util/storage.ts'
import StorageModuleEnum from '@model/enum/StorageModuleEnum'
import { getModuleListV2 } from '@src/modules/connector/api/trigger.js'
import { isArray } from 'lodash'

/** 
 * @description 获取模块列表
*/
function useConnectorCardSettingFetchModuleList(fromPageType: string) {
  
  // 加载状态
  const { loading, setLoading, clearLoading } = useLoading()
  
  // 模块App列表
  const moduleList: Ref<ConnectorAppModuleListItem[]> = ref([])
  // 模块列表
  const moduleListItem: Ref<ConnectorAppModuleListItem[]> = ref([])

  // 触发器模块列表
  const moduleTriggerListItem: Ref<ConnectorAppModuleListItem[]> = ref([])
  
  const fetchModuleList = (params: ConnectorGetModuleListParams) => {
    
    setLoading()
    
    return (
      (fromPageType === 'newTrigger' ? getModuleAppListV2 : getModuleAppList)(params).then(result => {
        
        if (MsgModel.isSuccess(result)) {
          moduleList.value = result?.data || []
          
        } else {
          message.error(result?.message || ConnectorModuleErrorMessageEnum.ModuleList)
        }
        
        return moduleList.value
        
      })
        .catch(error => {
          
          Log.error(error, fetchModuleList.name)
          
          return [] as ConnectorAppModuleListItem[]
          
        })
        .finally(() => {
          
          clearLoading()
          
        })
    )
  }

  const fetchModuleItemList = async (params: Record<string, any>) => {
    
    setLoading()
    const cacheData = await storageGet(ConnectorFetchAppModulesStorageKey + params.appId, [], StorageModuleEnum.Connector, false)
    if(Array.isArray(cacheData) && cacheData.length > 0) {
      moduleListItem.value = cacheData
      return Promise.resolve(cacheData)
    }
    
    return (
      getModuleAppItemsList(params).then(result => {
        
        if (MsgModel.isSuccess(result)) {
  
          moduleListItem.value = result?.data || []
          
        } else {
          message.error(result?.message || ConnectorModuleErrorMessageEnum.ModuleList)
        }

        storageSet(ConnectorFetchAppModulesStorageKey + params.appId, moduleListItem.value, StorageModuleEnum.Connector, false)
        
        return moduleList.value
        
      })
        .catch(error => {
          
          Log.error(error, getModuleAppItemsList.name)
          
          return [] as ConnectorAppModuleListItem[]
          
        })
        .finally(() => {
          
          clearLoading()
          
        })
    )
  }


  const fetchTriggerModuleItemList = async (params: Record<string, any>) => {
    
    setLoading()
    // const cacheData = await storageGet(ConnectorFetchAppModulesStorageKey + params.appId, [], StorageModuleEnum.Connector, false)
    // if(Array.isArray(cacheData) && cacheData.length > 0) {
    //   moduleListItem.value = cacheData
    //   return Promise.resolve(cacheData)
    // }
    
    return (
      getModuleListV2(params).then(result => {
        
        if (MsgModel.isSuccess(result)) {
  
          moduleTriggerListItem.value = result?.data || []
          
        } else {
          message.error(result?.message || ConnectorModuleErrorMessageEnum.ModuleList)
        }

        // storageSet(ConnectorFetchAppModulesStorageKey + params.appId, moduleListItem.value, StorageModuleEnum.Connector, false)
        
        return moduleList.value
        
      })
        .catch(error => {
          
          Log.error(error, fetchTriggerModuleItemList.name)
          
          return [] as ConnectorAppModuleListItem[]
          
        })
        .finally(() => {
          
          clearLoading()
          
        })
    )
  }
  
  return {
    fetchModuleList,
    fetchModuleItemList,
    fetchTriggerModuleItemList,
    moduleTriggerListItem,
    moduleListItem,
    moduleList,
    loading
  }
}

/** 
 * @description 获取连接器配置
*/
function useConnectorCardSettingFetchConnectorOptions() {
  
  // 加载状态
  const { loading, setLoading, clearLoading } = useLoading()
  
  // 连接器配置
  const connectorOptions: Ref<ConnectorOptions> = ref(ConnectorDefaultOptions)
  
  const fetchConnectorOptions = (params: ConnectorGetOptionsParams) => {
    
    setLoading()
    
    return (
      getConnectorOptionsV2(params).then(result => {
        
        if (MsgModel.isSuccess(result)) {
          
          const connectorOptionsResult = result.data || ConnectorDefaultOptions
          
          connectorOptionsExtraCompatibleHandler(
            connectorOptionsResult,
            params.toBizType,
            params.toBizTypeId
          )
          
          connectorOptions.value = connectorOptionsResult
          
        } else {
          message.error(result?.message || ConnectorModuleErrorMessageEnum.ConnectorOptions)
        }
        return connectorOptions.value
        
      })
      .catch(error => {
        
        Log.error(error, fetchConnectorOptions.name)
        
        return ConnectorDefaultOptions
        
      })
      .finally(() => {
        
        clearLoading()
        
      })
    )
  }
  
  return {
    fetchConnectorOptions,
    connectorOptions,
    loading
  }
}

/** 
 * @description 获取编辑连接器配置
*/
function useConnectorCardSettingFetchEditConnectorOptions() {
  
  // 加载状态
  const { loading, setLoading, clearLoading } = useLoading()
  
  // 连接器编辑配置
  const connectorEditOptions: Ref<ConnectorEditOptions> = ref(ConnectorDefaultEditOptions)
  
  const fetchConnectorEditOptions = (params: ConnectorGetEditOptionsParams) => {
    
    setLoading()
    
    return (
      getEditConnectorOptionsV2(params).then(result => {
        
        if (MsgModel.isSuccess(result)) {
          
          const connectorEditOptionsResult: ConnectorEditOptions = (result.data || ConnectorDefaultOptions) as ConnectorEditOptions
          
          connectorOptionsExtraCompatibleHandler(
            connectorEditOptionsResult,
            params.toBizType,
            params.toBizTypeId
          )


          // 注释 暂时不需要 （工单中没有子表单 不需要支持json Array）
          // if(Reflect.has(connectorEditOptionsResult, 'actionList') && isArray(connectorEditOptionsResult.actionList)) {
          //   connectorEditOptionsResult.actionList.map(action=> {
          //     return covertSetForDataKey(action, ['toRequestFieldList', 'toResponseFieldList'], ['supportDelete', 'supportInsert', 'supportSelect', 'supportUpdate'])
          //   })
          // }

          
          connectorEditOptions.value = connectorEditOptionsResult
          
        } else {
          message.error(result?.message || ConnectorModuleErrorMessageEnum.ConnectorOptions)
        }
        
        return connectorEditOptions.value
        
      })
      .catch(error => {
        
        Log.error(error, fetchConnectorEditOptions.name)
        
        return ConnectorDefaultEditOptions
        
      })
      .finally(() => {
        
        clearLoading()
        
      })
    )
  }
  
  return {
    fetchConnectorEditOptions,
    connectorEditOptions,
    loading
  }
}

/** 
 * @description 保存连接器配置
*/
function useConnectorCardSettingFetchSaveConnectorOptions() {
  
  // 加载状态
  const { loading, setLoading, clearLoading } = useLoading()
  
  const fetchSaveConnectorOptions = (params: ConnectorSaveOptionsParams) => {
    
    setLoading()
    
    return (
      saveConnectorOptionsV2(params).then(result => {
        
        if (MsgModel.isFail(result)) {
          
          message.error(result?.message || ConnectorModuleErrorMessageEnum.SaveConnectorOptions)
          
          return Promise.reject(result)
          
        }
        
        return
        
      })
      .catch(error => {
        
        Log.error(error, fetchSaveConnectorOptions.name)
        
        return Promise.reject(error)
        
      })
      .finally(() => {
        
        clearLoading()
        
      })
    )
  }
  
  return {
    fetchSaveConnectorOptions,
    loading
  }
}

/** 
 * @description 检查连接器是否已经被创建
*/
function useConnectorCardSettingCheckConnector() {
  
  // 加载状态
  const { loading, setLoading, clearLoading } = useLoading()
  
  const checkConnector = (params: ConnectorGetOptionsParams) => {
    
    setLoading()
    
    return (
      checkConnectorCard(params).then(result => {
        
        if (MsgModel.isFail(result)) {
          
          // message.error(result?.message || ConnectorModuleErrorMessageEnum.ConnectorOptions)
          
          return Promise.reject(result)
          
        }
        
        return
        
      })
      .catch(error => {
        
        Log.error(error, checkConnectorCard.name)
        
        return Promise.reject(error)
        
      })
      .finally(() => {
        
        clearLoading()
        
      })
    )
  }
  
  return {
    checkConnector,
    loading
  }
}

export {
  useConnectorCardSettingFetchModuleList,
  useConnectorCardSettingFetchConnectorOptions,
  useConnectorCardSettingFetchEditConnectorOptions,
  useConnectorCardSettingFetchSaveConnectorOptions,
  useConnectorCardSettingCheckConnector
}
